<template>
<div id="root">
  <div class="todo-container">
    <div class="todo-wrap">
      <Header ref="headerinfo"></Header>
      <List :todoinfoList="todoinfoList" :deleteItem="deleteItem"></List>
      <Footer :todoinfoList="todoinfoList" :clearTodo="clearTodo"></Footer>
    </div>
  </div>
</div>
</template>

<script>
import Header from '@/components/MyHeader.vue'
import List from '@/components/MyList.vue'
import Footer from '@/components/MyFooter.vue'
export default {
  name: 'App',
  components: {
    Header,
    List,
    Footer
  },
  data () {
    return {
      // 后面[]是为了后面组件读取是可以使用数组的方法（比如length）
      todoinfoList: JSON.parse(localStorage.getItem('todosinfo')) || []
    }
  },
  methods: {
    // 组件通信的第二种方法（和Item删除联用）
    deleteItem(id) {
      this.todoinfoList = this.todoinfoList.filter((todo) => {
        return todo.id !== id
      })
    },
    // 清楚已经完成的todo项
    clearTodo() {
      this.todoinfoList = this.todoinfoList.filter((todo) => {
        return !todo.done
      })
    }
  },
  watch: {
    todoinfoList: {
      deep: true,
      handler(newval) {
        // 存储成json格式的数据
        localStorage.setItem('todosinfo', JSON.stringify(newval))
      }
    }
  },
  mounted () {
    // 父组件获取子组件的vc
    // App和Header组件进行自定义事件通信
    this.$refs.headerinfo.$on('todoinfo', (params) => {
      this.todoinfoList.unshift(params)
      // console.log(params)
    })
    // 处理双向勾选状态(App和item组件进行全局事件总线进行通信)
    // 接收方
    this.$bus.$on('handleCheck', (id, check) => {
      this.todoinfoList.forEach((todo) => {
        if (todo.id === id) {
          todo.done = check
        }
      })
    })
    // 点击底部按钮todo项全选
    // App和Footer进行全局事件总线通信
    this.$bus.$on('checkall', (check) => {
      this.todoinfoList.forEach((todo) => {
        todo.done = check
      })
    })
    // 接收编辑过得数据（Item中）参数是id项和修改的值
    this.$bus.$on('blurSendvalue', (id, value) => {
      this.todoinfoList.forEach((todo) => {
        if (todo.id === id) {
          todo.title = value
        }
      })
    })
  }
  // 测试nanoid
  // mounted () {
  //   console.log(this.todoinfoList[0].id)
  // }
}
</script>
<style lang="less" scoped>

</style>
